class MembershipsController < ApplicationController
  #layout "main", :except => [:new, :create]
  #filter_access_to :all
  layout 'slim'

  #
  #
  def new
    @artist = Artist.find(params[:artist_id])
    @artist_search = Artist.search(params[:search])

    if !params[:search].nil?  && !params[:search][:name_like].blank?
      @members = @artist_search.all
    end
	
	respond_to do |format|
	  format.html
	end
  end

  ##
  def search
    @artist = Artist.find(params[:artist_id])
    @artist_search = Artist.search(params[:searchlogic_search])

    if !params[:searchlogic_search].nil?  && !params[:searchlogic_search][:name_like].blank?
      @members = @artist_search.all
    end
	
  	respond_to do |format|
	  format.js {
	    render :update do |page|
		  page.replace_html("membership-search-results", :partial => "results",
		                            :locals => {:artist => @artist, :members => @members})
		end
	  }
	end
  
  end
  
  #
  #
  def create
    @artist = Artist.find(params[:artist_id])
    membership = Membership.new

    #New artist needs to be created
    if params[:name] != nil && params[:member_id].nil?
      new_artist = Artist.new(:name => params[:name])
      new_artist.save
    end

    #if its a group, set band_id to artist
    if @artist.is_group?
      membership.band_id = @artist.id

      #If the user selected someone, set it to that
      # otherwise set it to the new artist that was
      # created.
      if params[:member_id] != nil
        membership.member_id = params[:member_id]
      else
        membership.member_id = new_artist.id
      end
      
    else
      membership.member_id = @artist.id
  
      if params[:member_id] != nil
        membership.band_id = params[:member_id]
      else
        membership.band_id = new_artist.id
      end
    end

    #
    #
    if membership.save
      redirect_to edit_artist_path(@artist)
    else
      render :new
    end
  end

  #
  #
  def edit
    @membership = Membership.find(params[:id])

  end

  #
  #
  def update
    @membership = Membership.find(params[:id])
	
	respond_to do |format|
      if @membership.update_attributes(params[:membership])
        format.html {redirect_to_request_uri}
      else
        format.html {render :edit}
      end
	
	end
  end

  #
  #
  def destroy
    @membership = Membership.find(params[:id])

    #Hack to get around issues with after_destroy callback
    entry = Hash.new
    entry.store("Removed", [@membership.band.name, @membership.member.name])
    Edit.create_edit(entry, @membership.member)

    @membership.destroy    
    redirect_to_request_uri
  end

end
